package com.xq.utils;

import com.alibaba.fastjson.JSON;
import com.xq.pojo.User;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.I0Itec.zkclient.exception.ZkMarshallingError;
import org.I0Itec.zkclient.serialize.ZkSerializer;

import java.io.UnsupportedEncodingException;

/**
 * @author xq
 * @version 1.0
 * @date 2021/4/21 8:09
 * @description 将对象传给zk服务器，进行对字符串序列化
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class ObjectSerializer implements ZkSerializer {
    /**
     * default charset
     */
    private String charset = "UTF-8";

    /**
     * 序列化
     * @param obj 序序列化的对象
     * @return 返回序列化的字节数组
     */
    @Override
    public byte[] serialize(Object obj) throws ZkMarshallingError {
        // 将json转换为字符串
        String jsonString = JSON.toJSONString(obj);
        System.out.println(jsonString);
        try {
            // 将字节数组设置字节编码
            byte[] bytes = String.valueOf(jsonString).getBytes(charset);
            return bytes;
        }catch (UnsupportedEncodingException e) {
            throw new ZkMarshallingError("Wrong Charset：" + charset);
        }
    }

    /**
     * 反序列化
     * @param bytes 获取zk中的字节数组进行反序列化
     * @return 返回序列化的字节数组
     */
    @Override
    public Object deserialize(byte[] bytes) throws ZkMarshallingError {
        User user = null;
        try {
            // 设置字节数组转换为字符串进行编码设置
            String result = new String(bytes,charset);
            System.out.println(result);
            // 将json字符串转换成user对象
            user = JSON.parseObject(result, User.class);
        } catch (UnsupportedEncodingException e) {
            throw new ZkMarshallingError("Wrong Charset："+ charset);
        }
        return user;
    }
}
